package devin.chat.view.login;

import devin.chat.MainApp;
import devin.chat.view.BaseController;
import devin.chat.view.root.RootViewController;
import javafx.fxml.FXML;
import javafx.scene.control.PasswordField;
import javafx.scene.control.TextField;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyEvent;
import javafx.scene.text.Text;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author devin
 */
public class LoginViewController extends BaseController {

    /** 日志 */
    private static final Logger LOGGER = LoggerFactory.getLogger(LoginViewController.class);

    @FXML
    private Text txtTip;

    @FXML
    private TextField tfUsername;

    @FXML
    private PasswordField pfPassword;

    @FXML
    private void handleKeyPressed(KeyEvent event) {
        if (event.getCode() == KeyCode.ENTER) {
            validLogin();
            event.consume();
        }
    }

    @FXML
    private void handleSignAction() {
        validLogin();
    }

    private void validLogin() {
        // 校验有户名
        String username = tfUsername.getText();
        if (username == null || username.trim().isEmpty()) {
            txtTip.setText("username required!");
            tfUsername.requestFocus();
            LOGGER.warn("login require username");
            return;
        }

        // 校验密码
        String password = pfPassword.getText();
        if (password == null || password.trim().isEmpty()) {
            txtTip.setText("password required!");
            pfPassword.requestFocus();
            LOGGER.warn("login require password");
            return;
        }

        username = username.trim();
        password = password.trim();
        if ("admin".equals(username) && "admin".equals(password)) {
            LOGGER.info("[{}] login success", username);
            manager.closeStage(getClass().getName());
            manager.showStage(RootViewController.class.getName());
        } else { // 密码或用户名错误
            tfUsername.setText(null);
            pfPassword.setText(null);
            tfUsername.requestFocus();
            txtTip.setText("username or password error!");
            LOGGER.warn("[{}] login failure", username);
        }
    }
}
